package com.zlkj.pro.modular.app.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.mapper.UserMapper;
import com.zlkj.pro.modular.business.entity.*;
import com.zlkj.pro.modular.business.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.zlkj.pro.core.consts.ProjectConstants.SERVICE_APP_PREFIX;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@ApiResource(name = "批量导入", path = SERVICE_APP_PREFIX + "/batch")
public class BatchInsertController {

    private final TCustomerService customerService;

    private final CustomerContactsService customerContactsService;

    private final UserMapper userMapper;

    private final AgentService agentService;

    private final ProductInfoService productInfoService;

    private final ReportService reportService;

    private final ReportProductService reportProductService;


    @GetResource(name = "插入数据", path = "/insert")
    public ResponseData insert() throws ParseException {
        //extractedCustomer();//客户
        //extractedCustomerContact();//客户联系人
        extractedReport();//报备单
        return new SuccessResponseData(null);
    }

    private void extractedCustomer() throws ParseException {
        // 获取客户对应关系map
        Map<String, String> customerMap = getCustomerMap();

        // 避免重复插入客户
        Set<String> oldCustomerNameSet = new HashSet<>();
        Set<String> customerNameSet = new HashSet<>();

        // 定义Excel文件路径
        String filePath = "/Users/liyang/Downloads/副本报备表-240806.xlsx";
        // 使用Hutool的ExcelUtil获取ExcelReader实例
        ExcelReader reader = ExcelUtil.getReader(filePath);
        // 读取第二个Sheet页，默认情况下Sheet名称或索引都是从0开始，所以第二个Sheet的索引为1
        reader.setSheet(3);
        // 读取C到J列，注意列索引也是从0开始，因此C列是2，J列是9
        List<List<Object>> data = reader.read(2, 973); // 参数表示读取的起始列和结束列

        // 查询代理商数据
        List<AgentEntity> agentlist = agentService.list();

        // 查询用户数据
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getDelFlag, "N");
        List<User> userlist = userMapper.selectList(queryWrapper);

        // 收集旧数据
        List<CustomerEntity> customers = customerService.list();
        for (CustomerEntity customer : customers){
            String thisAgentName = agentlist.stream().filter(agentEntity -> agentEntity.getId().equals(customer.getAgentId())).findFirst().get().getName();
            oldCustomerNameSet.add(thisAgentName + customer.getName() + customer.getAddress());
        }

        // 打印读取的数据
        List<CustomerEntity> customerList = new ArrayList<>();
        for (List<Object> row : data) {
            String agentName = (String) row.get(1);
            String reportTime = row.get(2).toString();//报备时间
            String createTime = row.get(3).toString();
            String approveDate = row.get(5)==null?"":row.get(5).toString();//审批通过时间
            String reportStatus = (String) row.get(6);
            String transactionDate = row.get(7).toString();
            String smhCode = row.get(8).toString();//书名号
            String customerName = (String) row.get(9);
            String uscc = (String) row.get(10);//统一社会信用代码
            String customerType = (String) row.get(11);
            String address = (String) row.get(12);
            String addressDetail = (String) row.get(13);
            String makeAddress = row.get(14)==null?"":row.get(14).toString();//安装地址
            String level = (String) row.get(15);
            String productCode = row.get(16).toString();//产品型号
            String number = row.get(17).toString();//产品数量
            String name = (String) row.get(19);
            String phone = row.get(20).toString();


            // 设置id作更新操作
            CustomerEntity a = new CustomerEntity();
            if (!oldCustomerNameSet.add(agentName + customerName + addressDetail)) {
                System.out.println("重复插入客户：" + agentName + customerName + addressDetail);
                // 向 customerNameSet 中add一个name 判断set长度有没有发生变化
                if (!customerNameSet.add(agentName + customerName + addressDetail)) {
                    continue;
                }
                Long oldCustomerId = customers.stream().filter(customer ->
                        customer.getName().equals(customerName)
                                && customer.getAddress().equals(addressDetail)
                                && customer.getAgentId().equals(agentlist.stream().filter(agentEntity -> agentEntity.getName().equals(agentName)).findFirst().get().getId())
                ).findFirst().get().getId();
                a.setId(oldCustomerId);
            } else {
                // 向 customerNameSet 中add一个name 判断set长度有没有发生变化
                if (!customerNameSet.add(agentName + customerName + addressDetail)) {
                    continue;
                }
            }



            // 批量插入
            a.setName(customerName);
            if(customerName.equals("个体户")){
                a.setType(2);
            }else{
                a.setType(1);
            }
            // 分类处理
            if (StringUtils.isNotBlank(customerType)) {
                // 逗号分割customerType
                String[] customerTypeList = customerType.split("、");
                String Classify = "";
                for (String customerTypeItem : customerTypeList) {
                    if (customerMap.containsKey(customerTypeItem)) {
                        Classify += customerMap.get(customerTypeItem) + ",";
                    }
                }
                if (StringUtils.isNotBlank(Classify)) {
                    // 删除最后一个逗号
                    Classify = Classify.substring(0, Classify.length() - 1);
                }
                a.setClassify(Classify);
            }

            a.setAddress(addressDetail);
            a.setAddressDetail("");
            // 在agentlist里找到name = agentName的agentId
            System.out.println(agentName);
            a.setAgentId(agentlist.stream().filter(agentEntity -> agentEntity.getName().equals(agentName)).findFirst().get().getId());

            if (StringUtils.isNotBlank(level)) {
                if (level.equals("A")) {
                    a.setLevel(1);
                } else if (level.equals("B")) {
                    a.setLevel(2);
                } else if (level.equals("C")) {
                    a.setLevel(3);
                } else if (level.equals("S")) {
                    a.setLevel(4);
                }
            }
            if (StringUtils.isNotBlank(reportStatus) && reportStatus.equals("成交")) {
                a.setCustomerStatus(2);
            } else {
                a.setCustomerStatus(1);
            }

            a.setDataSort(1);
            if (StringUtils.isNotBlank(createTime)) {
                // 将2023/7/18 转化为Date
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                a.setCreateTime(formatter.parse(createTime));
            }
            if (StringUtils.isNotBlank(transactionDate)) {
                // 将2023/7/18 转化为LocalDate
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                a.setTransactionDate(LocalDate.from(LocalDateTime.parse(transactionDate, formatter)));
            }
            a.setCreateUser(userlist.stream().filter(entity -> entity.getRealName().equals(agentName)).findFirst().get().getUserId());
            a.setUpdateTime(new Date());
            a.setUpdateUser(a.getCreateUser());
            a.setDelFlag("N");
            a.setProvince(address);
            a.setUscc(uscc);
            customerList.add(a);
        }
        customerService.saveOrUpdateBatch(customerList);

        // 关闭reader以释放资源（如果需要）
        reader.close();
    }

    private Map<String, String> getCustomerMap() {
        Map<String, String> replacementMap = new HashMap<>();
        replacementMap.put("印绣", "刺绣");
        replacementMap.put("刺绣", "刺绣");
        replacementMap.put("绣花", "刺绣");
        replacementMap.put("数码科技公司", "店铺");
        replacementMap.put("店铺", "店铺");
        replacementMap.put("品牌", "店铺");
        replacementMap.put("品牌专卖店", "店铺");
        replacementMap.put("服装实体店", "店铺");
        replacementMap.put("服装门店", "店铺");
        replacementMap.put("服务", "店铺");
        replacementMap.put("文化公司", "店铺");
        replacementMap.put("文创", "店铺");
        replacementMap.put("有限公司", "店铺");
        replacementMap.put("旅游", "店铺");
        replacementMap.put("零食", "店铺");
        replacementMap.put("零售", "店铺");
        replacementMap.put("档口", "店铺");
        replacementMap.put("传媒公司", "店铺");
        replacementMap.put("创意公司", "店铺");
        replacementMap.put("发展公司", "店铺");
        replacementMap.put("图文", "店铺");
        replacementMap.put("图文行业", "店铺");
        replacementMap.put("实体店", "店铺");
        replacementMap.put("报备过期", "店铺");
        replacementMap.put("线下", "店铺");
        replacementMap.put("线下门店", "店铺");
        replacementMap.put("销售", "店铺");
        replacementMap.put("门店", "店铺");
        replacementMap.put("T恤", "服装厂");
        replacementMap.put("家居用品", "服装厂");
        replacementMap.put("休闲裤", "服装厂");
        replacementMap.put("牛仔裤", "服装厂");
        replacementMap.put("国内服饰", "服装厂");
        replacementMap.put("国内帽业", "服装厂");
        replacementMap.put("沙滩裤", "服装厂");
        replacementMap.put("女装", "服装厂");
        replacementMap.put("商校文化衫", "服装厂");
        replacementMap.put("情侣装", "服装厂");
        replacementMap.put("制衣", "服装厂");
        replacementMap.put("制衣厂", "服装厂");
        replacementMap.put("体育服装", "服装厂");
        replacementMap.put("体育服装销售", "服装厂");
        replacementMap.put("体育用品", "服装厂");
        replacementMap.put("男装", "服装厂");
        replacementMap.put("中山市鑫泰源服饰有限公司", "服装厂");
        replacementMap.put("童装", "服装厂");
        replacementMap.put("童鞋", "服装厂");
        replacementMap.put("内衣", "服装厂");
        replacementMap.put("内裤", "服装厂");
        replacementMap.put("箱包", "服装厂");
        replacementMap.put("帆布鞋工厂", "服装厂");
        replacementMap.put("批发", "服装厂");
        replacementMap.put("服装", "服装厂");
        replacementMap.put("服装加工", "服装厂");
        replacementMap.put("服装公司", "服装厂");
        replacementMap.put("服装工厂", "服装厂");
        replacementMap.put("服装行业", "服装厂");
        replacementMap.put("服装生产", "服装厂");
        replacementMap.put("服装潮牌", "服装厂");
        replacementMap.put("服装定制", "服装厂");
        replacementMap.put("服装店", "服装厂");
        replacementMap.put("服装零售批发", "服装厂");
        replacementMap.put("服装厂", "服装厂");
        replacementMap.put("服装鞋帽", "服装厂");
        replacementMap.put("服装设计", "服装厂");
        replacementMap.put("服装贸易", "服装厂");
        replacementMap.put("服装辅料", "服装厂");
        replacementMap.put("服装销售", "服装厂");
        replacementMap.put("服帽", "服装厂");
        replacementMap.put("服饰", "服装厂");
        replacementMap.put("服饰公司", "服装厂");
        replacementMap.put("文化衫", "服装厂");
        replacementMap.put("文化衫定做团体服定制", "服装厂");
        replacementMap.put("包装", "服装厂");
        replacementMap.put("帽子", "服装厂");
        replacementMap.put("广告衫", "服装厂");
        replacementMap.put("鞋", "服装厂");
        replacementMap.put("鞋帽", "服装厂");
        replacementMap.put("鞋帽批发", "服装厂");
        replacementMap.put("亲子装定制", "服装厂");
        replacementMap.put("团体服定制", "服装厂");
        replacementMap.put("头饰", "服装厂");
        replacementMap.put("婴儿用品公司", "服装厂");
        replacementMap.put("样板间", "服装厂");
        replacementMap.put("纺织", "服装厂");
        replacementMap.put("纺织公司", "服装厂");
        replacementMap.put("纺织服饰", "服装厂");
        replacementMap.put("运动服", "服装厂");
        replacementMap.put("针织", "服装厂");
        replacementMap.put("针织裤", "服装厂");
        replacementMap.put("靓仔裤", "服装厂");
        replacementMap.put("饰品", "服装厂");
        replacementMap.put("广告", "广告");
        replacementMap.put("广告公司", "广告");
        replacementMap.put("健身", "国内电商");
        replacementMap.put("工作室", "国内电商");
        replacementMap.put("国内電商", "国内电商");
        replacementMap.put("国内电商", "国内电商");
        replacementMap.put("人工智能", "国内电商");
        replacementMap.put("直播", "国内电商");
        replacementMap.put("服装电商", "国内电商");
        replacementMap.put("个人", "国内电商");
        replacementMap.put("个人客户", "国内电商");
        replacementMap.put("个人电商", "国内电商");
        replacementMap.put("个体户", "国内电商");
        replacementMap.put("抖音客户", "国内电商");
        replacementMap.put("电子公司", "国内电商");
        replacementMap.put("电商", "国内电商");
        replacementMap.put("电商客户", "国内电商");
        replacementMap.put("电商公司", "国内电商");
        replacementMap.put("设计", "国内电商");
        replacementMap.put("设计公司", "国内电商");
        replacementMap.put("软件开发", "国内电商");
        replacementMap.put("外贸电商", "跨境电商");
        replacementMap.put("跨境电商", "跨境电商");
        replacementMap.put("外贸", "外贸");
        replacementMap.put("外贸公司", "外贸");
        replacementMap.put("外贸服装", "外贸");
        replacementMap.put("国内贸易", "外贸");
        replacementMap.put("鞋帽贸易", "外贸");
        replacementMap.put("贸易", "外贸");
        replacementMap.put("贸易公司", "外贸");
        replacementMap.put("贸易服装", "外贸");
        replacementMap.put("进出", "外贸");
        replacementMap.put("进出口贸易", "外贸");
        replacementMap.put("学校", "学校");
        replacementMap.put("学校团体服定制", "学校");
        replacementMap.put("技术学院", "学校");
        replacementMap.put("教育", "学校");
        replacementMap.put("工艺", "学校");
        replacementMap.put("工艺美术品", "学校");
        replacementMap.put("大学教学使用", "学校");
        replacementMap.put("实验室", "学校");
        replacementMap.put("艺术创作", "学校");
        replacementMap.put("印花", "印花加工厂");
        replacementMap.put("印花加工", "印花加工厂");
        replacementMap.put("印花加工厂", "印花加工厂");
        replacementMap.put("印花公司", "印花加工厂");
        replacementMap.put("印花工厂", "印花加工厂");
        replacementMap.put("印花厂", "印花加工厂");
        replacementMap.put("印刷", "印花加工厂");
        replacementMap.put("印刷公司", "印花加工厂");
        replacementMap.put("印染", "印花加工厂");
        replacementMap.put("加工", "印花加工厂");
        replacementMap.put("加工工厂", "印花加工厂");
        replacementMap.put("加工童装", "印花加工厂");
        replacementMap.put("科技公司", "印花加工厂");
        replacementMap.put("企业", "印花加工厂");
        replacementMap.put("机械工厂", "印花加工厂");
        replacementMap.put("供应链", "印花加工厂");
        replacementMap.put("供应链管理", "印花加工厂");
        replacementMap.put("公司", "印花加工厂");
        replacementMap.put("工厂", "印花加工厂");
        replacementMap.put("刻字膜", "印花加工厂");
        replacementMap.put("国内工厂", "印花加工厂");
        replacementMap.put("国内工艺品", "印花加工厂");
        replacementMap.put("国内纺织", "印花加工厂");
        replacementMap.put("裁片", "印花加工厂");
        replacementMap.put("数码", "印花加工厂");
        replacementMap.put("数码印花", "印花加工厂");
        replacementMap.put("数码加工", "印花加工厂");
        replacementMap.put("生产", "印花加工厂");
        replacementMap.put("租赁", "印花加工厂");
        replacementMap.put("代理商", "印花加工厂");
        replacementMap.put("中山市赤道文化传播有限公司", "印花加工厂");
        replacementMap.put("直喷", "印花加工厂");
        replacementMap.put("定制", "印花加工厂");
        replacementMap.put("二级代理", "印花加工厂");
        replacementMap.put("二级代理商", "印花加工厂");
        replacementMap.put("布袋定制", "印花加工厂");
        replacementMap.put("布料批发", "印花加工厂");
        replacementMap.put("面料批发", "印花加工厂");
        replacementMap.put("礼品", "印花加工厂");
        replacementMap.put("个性化定制", "印花加工厂");
        replacementMap.put("个性化定制服务", "印花加工厂");
        replacementMap.put("个性定制", "印花加工厂");
        replacementMap.put("鞋子加工", "印花加工厂");
        replacementMap.put("丝印", "印花加工厂");
        replacementMap.put("丝网印", "印花加工厂");
        replacementMap.put("标牌贴花", "印花加工厂");
        replacementMap.put("样机", "印花加工厂");
        replacementMap.put("烫画", "印花加工厂");
        replacementMap.put("经销商", "印花加工厂");
        replacementMap.put("设备", "印花加工厂");
        replacementMap.put("锦里供应链", "印花加工厂");
        return replacementMap;
    }

    private void extractedCustomerContact() throws ParseException {
        // 避免重复插入客户
        Set<String> customerContactNameSet = new HashSet<>();

        // 定义Excel文件路径
        String filePath = "/Users/liyang/Downloads/副本报备表-240806.xlsx";
        // 使用Hutool的ExcelUtil获取ExcelReader实例
        ExcelReader reader = ExcelUtil.getReader(filePath);
        // 读取第二个Sheet页，默认情况下Sheet名称或索引都是从0开始，所以第二个Sheet的索引为1
        reader.setSheet(3);
        // 读取C到J列，注意列索引也是从0开始，因此C列是2，J列是9
        List<List<Object>> data = reader.read(2, 973); // 参数表示读取的起始列和结束列

        // 查询代理商数据
        List<AgentEntity> agentlist = agentService.list();

        // 查询客户数据
        List<CustomerEntity> customerList = customerService.list();

        // 查询用户数据
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getDelFlag, "N");
        List<User> userlist = userMapper.selectList(queryWrapper);

        // 打印读取的数据
        List<CustomerContactsEntity> contactList = new ArrayList<>();
        for (List<Object> row : data) {
            String agentName = (String) row.get(1);
            String reportTime = row.get(2).toString();//报备时间
            String createTime = row.get(3).toString();
            String approveDate = row.get(5)==null?"":row.get(5).toString();//审批通过时间
            String reportStatus = (String) row.get(6);
            String transactionDate = row.get(7).toString();
            String smhCode = row.get(8).toString();//书名号
            String customerName = (String) row.get(9);
            String uscc = (String) row.get(10);//统一社会信用代码
            String customerType = (String) row.get(11);
            String address = (String) row.get(12);
            String addressDetail = (String) row.get(13);
            String makeAddress = row.get(14)==null?"":row.get(14).toString();//安装地址
            String level = (String) row.get(15);
            String productCode = row.get(16).toString();//产品型号
            String number = row.get(17).toString();//产品数量
            String name = (String) row.get(19);
            String phone = row.get(20).toString();

            // 向 customerNameSet 中add一个name 判断set长度有没有发生变化
            if (!customerContactNameSet.add(agentName + customerName + addressDetail + name)) {
                continue;
            }

            // 批量插入
            CustomerContactsEntity a = new CustomerContactsEntity();
            a.setName(name);
            a.setPhone(phone);
            a.setEmail("");
            Long agentId = agentlist.stream().filter(agentEntity -> agentEntity.getName().equals(agentName)).findFirst().get().getId();
            System.out.println(customerName + "/" + addressDetail + "/" + agentId);
            a.setCustomerId(Math.toIntExact(customerList.stream().filter(entity ->
                    entity.getName().equals(customerName)
                            && entity.getAddress().equals(addressDetail)
                            && entity.getAgentId().equals(agentId)).findFirst().get().getId()));
            a.setContactStatus(1);
            a.setDataSort(1);
            a.setRemark("");
            a.setStatusFlag(1);
            if (StringUtils.isNotBlank(createTime)) {
                // 将2023/7/18 转化为Date
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                a.setCreateTime(formatter.parse(createTime));
            }
            a.setCreateUser(userlist.stream().filter(entity -> entity.getRealName().equals(agentName)).findFirst().get().getUserId());
            a.setUpdateTime(new Date());
            a.setUpdateUser(a.getCreateUser());
            a.setDelFlag("N");
            contactList.add(a);
        }
        customerContactsService.saveBatch(contactList);

        // 关闭reader以释放资源（如果需要）
        reader.close();
    }


    public static void main(String[] args) {
        System.out.println(RandomUtil.randomLong(10000000000000000L, 20000000000000000L));
    }

    private void extractedReport() throws ParseException {

        // 定义Excel文件路径
        String filePath = "/Users/liyang/Downloads/副本报备表-240806.xlsx";
        // 使用Hutool的ExcelUtil获取ExcelReader实例
        ExcelReader reader = ExcelUtil.getReader(filePath);
        // 读取第二个Sheet页，默认情况下Sheet名称或索引都是从0开始，所以第二个Sheet的索引为1
        reader.setSheet(3);
        // 读取C到J列，注意列索引也是从0开始，因此C列是2，J列是9
        List<List<Object>> data = reader.read(2, 973); // 参数表示读取的起始列和结束列

        // 查询代理商数据
        List<AgentEntity> agentlist = agentService.list();

        // 查询客户数据
        List<CustomerEntity> customerList = customerService.list();

        // 查询客户联系人数据
        List<CustomerContactsEntity> customerContactsList = customerContactsService.list();

        // 查询用户数据
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getDelFlag, "N");
        List<User> userlist = userMapper.selectList(queryWrapper);

        // 查询产品数据
        List<ProductInfoEntity> productInfoList = productInfoService.list();

        // 打印读取的数据
        List<ReportEntity> reportList = new ArrayList<>();
        List<ReportProductEntity> reportProductList = new ArrayList<>();

        for (List<Object> row : data) {
            String agentName = (String) row.get(1);
            String reportTime = row.get(2).toString();//报备时间
            String createTime = row.get(3).toString();
            String approveDate = row.get(5)==null?"":row.get(5).toString();//审批通过时间
            String reportStatus = (String) row.get(6);
            String transactionDate = row.get(7).toString();
            String smhCode = row.get(8).toString();//书名号
            String customerName = (String) row.get(9);
            String uscc = (String) row.get(10);//统一社会信用代码
            String customerType = (String) row.get(11);
            String address = (String) row.get(12);
            String addressDetail = (String) row.get(13);
            String makeAddress = row.get(14)==null?"":row.get(14).toString();//安装地址
            String level = (String) row.get(15);
            String productCode = row.get(16).toString();//产品型号
            String number = row.get(17).toString();//产品数量
            String name = (String) row.get(19);
            String phone = row.get(20).toString();

            // 批量插入
            ReportEntity a = new ReportEntity();
            a.setId(RandomUtil.randomLong(10000000000000000L, 20000000000000000L));
            // 生成四位随机数字符串
            String random = String.format("%04d", (int) (Math.random() * 10000));
            // reportTime截取前10位替换掉“-”
            String reportTimeChar = reportTime.substring(0, 10).replace("-", "");
            a.setCode("BMSH-" + reportTimeChar + "-" + random);
            if (StringUtils.isNotBlank(reportStatus) && reportStatus.equals("成交")) {
                a.setStatus(3);
            } else {
                a.setStatus(2);
            }
            a.setConferStatus(1);
            if (StringUtils.isNotBlank(smhCode)) {
                a.setCertificateStatus(2);
            } else {
                a.setCertificateStatus(1);
            }
            Long agentId = agentlist.stream().filter(agentEntity -> agentEntity.getName().equals(agentName)).findFirst().get().getId();
            a.setAgentId(agentId);

            System.out.println(customerName + "/" + addressDetail + "/" + agentId);
            // 客户信息
            CustomerEntity customer = customerList.stream().filter(entity -> entity.getName().equals(customerName)
                    && entity.getAddress().equals(addressDetail)
                    && entity.getAgentId().equals(agentId)).findFirst().get();
            a.setCustomerId(customer.getId());
            a.setCustomerName(customer.getName());
            a.setCustomerType(customer.getType());
            a.setCustomerClassify(customer.getClassify());
            a.setCustomerAddress(customer.getAddress());
            a.setCustomerAddressDetail("");
            a.setCustomerLevel(customer.getLevel());
            a.setCustomerStatus(customer.getCustomerStatus());
            a.setCustomerUscc(customer.getUscc());
            a.setCustomerRemark(customer.getRemark());
            // 客户联系人信息
            System.out.println(name + "/" + customer.getId());
            CustomerContactsEntity contact = customerContactsList.stream().filter(entity -> entity.getName().equals(name)
                    && Long.valueOf(entity.getCustomerId()).equals(customer.getId())).findFirst().get();

            a.setCustomerContactsName(contact.getName());
            a.setCustomerContactsPhone(contact.getPhone());
            a.setInvalidSource("");
            a.setInvalidReason("");

            // 将2023/7/18 转化为LocalDate
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            a.setExpirationDateStart(LocalDate.from(LocalDateTime.parse(reportTime, formatter)));
            a.setExpirationDateEnd(LocalDate.from(LocalDateTime.parse("2024-12-31 00:00:00", formatter)));
            a.setDelayDate(null);
            a.setDelayReason(null);
            a.setRemark(null);
            a.setApplyEndDate(null);
            if (StringUtils.isNotBlank(transactionDate)) {
                a.setTransactionDate(LocalDate.from(LocalDateTime.parse(transactionDate, formatter)));
            }
            if (StringUtils.isNotBlank(approveDate)) {
                a.setApproveDate(LocalDate.from(LocalDateTime.parse(approveDate, formatter)));
            }
            SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            a.setCreateTime(dateformatter.parse(reportTime));
            a.setCreateUser(userlist.stream().filter(entity -> entity.getRealName().equals(agentName)).findFirst().get().getUserId());
            a.setUpdateTime(new Date());
            a.setUpdateUser(a.getCreateUser());
            a.setDelFlag("N");
            a.setDelayApplyTime(null);
            a.setDelayCreateUserId(null);
            a.setDelayPassTime(null);
            a.setDelayPassUserId(null);
            a.setInstallAddress(makeAddress);
            a.setWhyAutoFail(null);
            reportList.add(a);


            ReportProductEntity p = new ReportProductEntity();
            p.setReportId(a.getId());
            System.out.println(productCode);
            ProductInfoEntity product = productInfoList.stream().filter(entity -> entity.getCode().equals(productCode)).findFirst().get();
            p.setProductId(product.getId());
            p.setName(product.getName());
            p.setCode(product.getCode());
            p.setProductTypeId(product.getProductTypeId());
            p.setImageDetailFileId(product.getImageDetailFileId());
            p.setManualFileId(product.getManualFileId());
            p.setPrice(product.getPrice());
            p.setIntroduce(product.getIntroduce());
            p.setNumber(Integer.valueOf(number));
            p.setCertificateCode(smhCode);
            if (StringUtils.isNotBlank(smhCode)) {
                p.setCertificateStatus(2);
            } else {
                p.setCertificateStatus(1);
            }
            p.setRemark("");
            p.setCreateTime(a.getCreateTime());
            p.setCreateUser(a.getCreateUser());
            p.setUpdateTime(a.getUpdateTime());
            p.setUpdateUser(a.getUpdateUser());
            p.setDelFlag("N");
            reportProductList.add(p);
        }

        // 批量插入报备单
        reportService.saveBatch(reportList);
        // 批量插入报备单产品
        reportProductService.saveBatch(reportProductList);
        // 关闭reader以释放资源（如果需要）
        reader.close();
    }

}
